﻿using NetWing.BPM.Core;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using NetWing.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Omu.ValueInjecter;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;

namespace NetWing.BPM.Admin.sparepartszhu.ashx
{
    /// <summary>
    /// sparepartszh_add 的摘要说明
    /// </summary>
    public class sparepartszh_add : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            string edNumber = common.mjcommon.getedNumbere("lp");
            int mainInsertedId = 0;//（主表公用）主表插入的ID
            int fmainInsertedId = 0;//财务主表插入的ID
            //这里可以执行一些逻辑
            if (string.IsNullOrEmpty(main) || string.IsNullOrEmpty(detail))
            {
                context.Response.Write("{\"status\":0,\"msg\":\"失败！主表或子表信息为空！\"}");
                context.Response.End();//输出结束
            }
            #region 主表处理
            JObject jh = (JObject)JsonConvert.DeserializeObject(main);
            var mainobj = JSONhelper.ConvertToObject<SparepartszhuModel>(main);//根据模型把json数据转化为obj
            SparepartszhuModel mainModel = new SparepartszhuModel();//初始化主表模型
            mainModel.InjectFrom(mainobj);//把obj插入模型
            mainModel.add_time = DateTime.Now;//给主表添加时间和更新时间赋值，其他字段赋值以此类推
            mainModel.jh_time = DateTime.Parse(jh["jhdate"].ToString());
            mainModel.order_sn = jh["orderid"].ToString();
            mainModel.comname = jh["unit"].ToString();//客户名称
            mainModel.salesman = jh["Contacts"].ToString();//业务员
            mainModel.kdy = SysVisitor.Instance.cookiesUserName;//开单员
            mainModel.unit_man = jh["unit_man"].ToString();//
            mainModel.ordername = jh["ordernameCopy"].ToString();//订单名称
            mainModel.ordernuber = jh["ordernuber"].ToString();//订单数量
            mainModel.gg = jh["gg"].ToString();//规格
            #endregion
            #region 子表明细表处理
            JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
            #endregion
            #region 数据库事务
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条
                

                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {

                    

                    JObject jo = (JObject)JsonConvert.DeserializeObject(detailArr[i].ToString());



                    var detailobj = JSONhelper.ConvertToObject<SparepartsModel>(detailArr[i].ToString());//根据模型把明细表转化为obj
                    SparepartsModel detailModel = new SparepartsModel();//初始化明细表模型
                    detailModel.InjectFrom(detailobj);//把obj插入模型
                    detailModel.order_sn = mainModel.order_sn;//单号
                    detailModel.okeyid = mainInsertedId.ToString();
                    detailModel.productname = string.IsNullOrEmpty(jo["productname"].ToString())?"空": jo["productname"].ToString();//生产产品名称
                    detailModel.material = string.IsNullOrEmpty(jo["material"].ToString())?"空": jo["material"].ToString(); //材料
                    detailModel.specifications = string.IsNullOrEmpty(jo["specifications"].ToString())?"空": jo["specifications"].ToString();//规格
                    detailModel.number = string.IsNullOrEmpty(jo["number"].ToString())?"空": jo["number"].ToString();//数量
                    detailModel.materialopening = string.IsNullOrEmpty(jo["materialopening"].ToString())?"空": jo["materialopening"].ToString();//开料规格
                    detailModel.technology = string.IsNullOrEmpty(jo["technology"].ToString())?"空": jo["technology"].ToString();//工艺要求
                    detailModel.note = string.IsNullOrEmpty(jo["note"].ToString())?"空": jo["note"].ToString();//备注
                    if(jo["billingclerk"].ToString() != null) { 
                    DataTable dataTable = SqlEasy.ExecuteDataTable("select * from Sys_Users where TrueName='" + jo["billingclerk"].ToString() + "'");
                    detailModel.billingclerk = string.IsNullOrEmpty(dataTable.Rows[0]["TrueName"].ToString())?"空": dataTable.Rows[0]["TrueName"].ToString();//备料员
                    detailModel.tell = string.IsNullOrEmpty(dataTable.Rows[0]["Mobile"].ToString())?"空": dataTable.Rows[0]["Mobile"].ToString();//备料员手机号
                    
                    

                    detailModel.wechareopen = string.IsNullOrEmpty(dataTable.Rows[0]["OpenID"].ToString())?"空": dataTable.Rows[0]["OpenID"].ToString();//备料员openid
                    }
                    DbUtils.tranInsert(detailModel, tran);
                    detailModel.cailiao = string.IsNullOrEmpty(jo["cailiao"].ToString()) ? "空" : jo["cailiao"].ToString();//材料成本
                    //采购时要更新商品价格为+数，examine_status为1时不写进Psi_Goods数据库
                    //string stocksql = "update Psi_Goods set stock=stock+" + detailModel.buyNum + ",buyprice="+(-detailModel.buyPrice)+",up_time='"+DateTime.Now.ToString()+"' where keyid=" + detailModel.goodsId + "";
                    //DbUtils.tranExecuteNonQuery(stocksql, tran);
                }
                //为模版中的各属性赋值
                var templateData = new ProductTemplateData()
                {
                    first = new TemplateDataItem(SysVisitor.Instance.cookiesUserName + "请您审核以下备料订单：JYD" + jh["orderid"].ToString(), "#000000"),
                    keyword1 = new TemplateDataItem(jh["ordername"].ToString(), "#000000"),
                    keyword2 = new TemplateDataItem("空。数量:"+jh["ordernuber"].ToString(), "#000000"),
                    keyword3 = new TemplateDataItem(DateTime.Now.ToString(), "#000000"),



                    keyword4 = new TemplateDataItem(jh["unit"].ToString(), "#000000"),
                    remark = new TemplateDataItem("备注:" + jh["unit_man"].ToString() + "，请尽快审核！", "#000000")
                };
                string templateid = NetWing.Common.ConfigHelper.GetValue("templageid2");//从web.config 获得模板ID
                                                                                        //通知所有员工就是openid不同
                DataTable dt = SqlEasy.ExecuteDataTable("select * from Sys_Users where openid<>'' and IsAdmin = 1");




                foreach (DataRow ndr in dt.Rows)
                {
                    string openid = ndr["openid"].ToString();
                    string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(openid, templateid, NetWing.Common.ConfigHelper.GetValue("website") + "JydModleOrder/bldsh.aspx", templateData);
                }
                tran.Commit();//提交执行事务
                context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");
            }
            #endregion
            catch (Exception e)
            {
                tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                throw;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}